<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>考核管理</a-breadcrumb-item>
      <a-breadcrumb-item>考核申报审核</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row>
      <a-col :span="18">
        申报时间范围：
        <a-range-picker
          style="width: 330px"
          v-model="creationDateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          @change="changeDate"
        />
      </a-col>
      <a-col :span="4">
        <a-button type="primary" @click="search()"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="reset">重置</a-button>
      </a-col>
    </a-row>
    <a-spin :spinning="loading">
      <a-row>
        <a-col :span="24">
          <div class="flex-between">
            <a-button
              v-hasPermi="['sbsh:rBtn']"
              type="primary"
              @click="handleOperation('Report')"
            >
              申述上报
            </a-button>
          </div>
          <div class="flex-between">
            <a-tabs v-model="queryForm.appealStatus" @change="changeTab">
              <a-tab-pane
                v-for="item in menuList"
                :key="item.value"
                :tab="item.label"
              >
              </a-tab-pane>
            </a-tabs>
          </div>
          <a-table
            :columns="columns"
            :data-source="tableData"
            :scroll="{ x: 1000 }"
            :pagination="false"
          >
            <span
              slot="action"
              slot-scope="text, record"
              v-if="queryForm.appealStatus == 0"
            >
              <!-- <a>查看</a>&nbsp;
                <a v-hasPermi="['khsb:audit']">审核</a> -->
              <a-divider type="vertical" />
              <a
                class="red"
                v-hasPermi="['sbsh:btn']"
                @click="clickCont2(text)"
                >驳回</a
              >
              <a-divider type="vertical" />
              <a
                class="blue"
                v-hasPermi="['sbsh:btn']"
                @click="clickCont(1, text)"
                >通过</a
              >
            </span>
            <!-- <span slot="appealStatus" slot-scope="text,record">
                {{ appealStatusList[record.appealStatus] }}
              </span> -->
          </a-table>
          <div class="page_box">
            <a-pagination
              v-model="queryForm.offset"
              :page-size-options="['20', '30', '40', '50']"
              :total="total"
              show-size-changer
              :page-size="queryForm.current"
              @showSizeChange="onShowSizeChange"
              @change="pageChange"
              :show-total="(total) => `共 ${total} 条`"
            ></a-pagination>
          </div>
        </a-col>
      </a-row>
    </a-spin>

    <a-modal
      title="是否确认驳回?"
      :visible="dialogVisible"
      cancel-text="取消"
      ok-text="确认"
      width="50%"
      @cancel="dialogVisible = false"
      @ok="handleSubmit"
    >
      <a-form
        :model="dataDialogFrom"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item label="驳回原因">
          <a-textarea
            v-model:value="dataDialogFrom.checkDesc"
            v-decorator="[
              'checkDesc',
              { rules: [{ required: true, message: '请输入驳回原因' }] },
            ]"
            :rows="4"
            placeholder="请输入驳回原因"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import { appealStatusList } from "./common";
import dayjs from "dayjs";
import moment from "moment";
import dictMixin from "@/mixins/dictMixin";
import { Modal } from "ant-design-vue";

const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",

  },
  {
    title: "申报状态",
    dataIndex: "appealStatus",
    key: "appealStatus",

    customRender: (text, record, index) => {
      console.log(text);
      return text == 0
        ? "未审核"
        : text == 1
        ? "已通过"
        : text == 2
        ? "已驳回"
        : "";
    },
  },
  {
    title: "审核意见",
    dataIndex: "checkDesc",
    key: "checkDesc",
  },
  {
    title: "取得社会影响",
    dataIndex: "contribute",
    key: "contribute",

  },
  {
    title: "申报类型",
    dataIndex: "appealType",
    key: "appealType",

  },
  {
    title: "申报主体",
    dataIndex: "appealBelong",
    key: "appealBelong",

  },
  {
    title: "分数",
    dataIndex: "getSocre",
    key: "getSocre",

  },
  {
    title: "申报人",
    dataIndex: "pusherUserName",
    key: "pusherUserName",

  },
  {
    title: "申报时间",
    dataIndex: "pusherTime",
    key: "pusherTime",

  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    fixed: "right",
  },
];

export default {
  mixins: [dictMixin],

  data() {
    return {
      tableData: [],
      columns,
      loading: false,
      eventVisible: false,
      appealStatusList: appealStatusList,
      queryForm: {
        current: 20,
        offset: 1,
        startTime: "",
        endTime: "",
        appealStatus: 0,
      },
      total: 0,
      tabsValue: null,
      menuList: [
        { label: "未审核", value: 0 },
        { label: "已通过", value: 1 },
        { label: "已驳回", value: 2 },
      ],
      creationDateRange: [],
      dialogVisible: false,
      dialogTitle: "",
      dataDialogFrom: {
        appealBelong: "",
        appealStatus: "",
        appealType: "个人",
        contribute: "",
        getSocre: "",
        getType: "",
        pusherTime: "",
        pusherUserId: "",
        xpiId: null,
        id: null,
      },
      appealStatusD: [
        { value: 0, label: "未审核" },
        { value: 1, label: "已通过" },
        { value: 2, label: "已驳回" },
      ],
      getTypeD: [
        { value: 0, label: "减分" },
        { value: 1, label: "加分" },
      ],
      pusherTimeData: [],
      indexValue: "",
      columns2: [
        {
          title: "", // 添加单选列
          dataIndex: "rowKey",
          key: "rowKey", // 自定义列的key，用于在模板中引用
          width: "50px",
        },
        { title: "事件编号", dataIndex: "eventId", key: "eventId" },
        {
          title: "受理状态",
          dataIndex: "businessStatus",
          key: "businessStatus",
          customRender: (text, record, index) => {
            // console.log(text)
            return text == 0
              ? "暂存"
              : text == 1
              ? "已上报"
              : text == 2
              ? "直接办结"
              : "";
          },
        },
        {
          title: "紧急程度",
          dataIndex: "urgencyLevel",
          key: "urgencyLevel",
          customRender: (text, record, index) => {
            // console.log(text)
            return text == 0
              ? "一般"
              : text == 1
              ? "优先"
              : text == 2
              ? "紧急"
              : "";
          },
        },
        {
          title: "办理状态",
          dataIndex: "eventStatus",
          key: "eventStatus",
          customRender: (text, record, index) => {
            // console.log(text)
            return (
              (this.dealStatusList.find((item) => item.value == text) || {})
                .label || ""
            );
          },
        },
        {
          title: "关联对象",
          dataIndex: "relatedObjectName",
          key: "relatedObjectName",
        },
        {
          title: "案件描述",
          dataIndex: "issueDescription",
          key: "issueDescription",
        },
        {
          title: "问题来源",
          dataIndex: "issueSource",
          key: "issueSource",
        },
        {
          title: "问题类型",
          dataIndex: "issueType",
          key: "issueType",
        },
        {
          title: "处理人用户名",
          dataIndex: "reporterName",
          key: "processUserName",
        },
        { title: "上报人姓名", dataIndex: "reporterName", key: "reporterName" },
        {
          title: "上报人电话",
          dataIndex: "reporterPhone",
          key: "reporterPhone",
        },
        { title: "上报时间", dataIndex: "reportTime", key: "reportTime" },
      ],
      tableData2: [],
      queryForm2: { current: 20, offset: 1 },
      total2: 0,
      loading2: false,
      selectedInputItemValue2: [], // 当前选中的行
    };
  },
  mounted() {
    let userInfo = JSON.parse(localStorage.getItem("userInfo"));

    this.dataDialogFrom.pusherUserId = userInfo.userId;
    this.dataDialogFrom.pusherTime = this.formatTimeDateTime();
    this.getList();
    // this.getPusher();
  },
  methods: {
    moment,
    // 分页
    onShowSizeChange(current, pageSize) {
      this.queryForm.offset = current;
      this.queryForm.current = pageSize;
      this.getList();
    },
    pageChange(current) {
      this.queryForm.offset = current;
      this.getList();
    },
    changeDate(val) {
      this.queryForm.startTime = val[0];
      this.queryForm.endTime = val[1];
    },
    // getList() {
    //   this.loading = true
    //   // const url1 = '/government-platform-center/socreAppeal?current='+this.queryForm.current+'&offset='+ this.queryForm.offset + '&startTime='+ this.queryForm.startTime +'&endTime=' + this.queryForm.endTime
    //   const url2 = '/government-platform-center/socreAppeal/getSocreAppealListForDept?current='+this.queryForm.current+'&offset='+ this.queryForm.offset + '&startTime='+ this.queryForm.startTime +'&endTime=' + this.queryForm.endTime +'&appealStatus='+this.queryForm.appealStatus
    //   this.$axios.get(url2).then((res) => {
    //     if (res.data.code == 0) {
    //       let data = res.data.data.map(item => ({
    //         ...item,
    //         pusherUserName: this.getUser(item.pusherUserId)
    //       }))
    //       console.log(data)
    //       this.tableData = data;
    //       this.total = res.data.total
    //       this.loading = false
    //     }
    //   })
    // },
    async getList() {
      try {
        this.loading = true;

        // 使用模板字符串提高可读性
        const baseUrl =
          "/government-platform-center/socreAppeal/getSocreAppealListForDept?current=" +
          this.queryForm.current +
          "&offset=" +
          this.queryForm.offset +
          "&startTime=" +
          this.queryForm.startTime +
          "&endTime=" +
          this.queryForm.endTime +
          "&appealStatus=" +
          this.queryForm.appealStatus;
        const res = await this.$axios.get(baseUrl);
        if (res.data.code !== 0) {
          throw new Error("请求失败: " + res.data.message);
        }

        // this.tableData = res.data.data;
        this.total = res.data.total;

        // 使用 Promise.all 并行处理所有用户请求
        this.tableData = await Promise.all(
          res.data.data.map(async (item) => ({
            ...item,
            // 直接添加 pusherUserName 字段到每行数据
            pusherUserName: await this.getUser(item.pusherUserId),
          }))
        );
        console.log("处理后的用户列表:", this.tableData);
      } catch (error) {
        console.error("获取列表失败:", error);
        this.$message.error("数据加载失败");
      } finally {
        this.loading = false;
      }
    },
    // 正确返回 Promise 的方法
    getUser(id) {
      return this.$axios
        .get("/government-platform-center/user/getUserInfo?userId=" + id)
        .then((res) => {
          return res.data.data.userName;
        })
        .catch((error) => {
          // 建议添加错误处理
          console.error("获取用户失败:", error);
          return "未知用户"; // 返回默认值
        });
    },
    search() {
      this.tableData = [];
      this.queryForm.offset = 1;
      this.getList();
    },
    reset() {
      this.tableData = [];
      this.creationDateRange = [];
      this.queryForm.offset = 1;
      this.queryForm.startTime = "";
      this.queryForm.endTime = "";
      this.getList();
    },
    handleOperation(index, data) {
      if (index == "edit") {
        console.log("编辑", data);
        this.dataDialogFrom = {
          appealBelong: data.appealBelong,
          appealStatus: data.appealStatus,
          appealType: "个人",
          contribute: data.contribute,
          getSocre: data.getSocre,
          getType: data.getType,
          pusherTime: data.pusherTime,
          pusherUserId: data.pusherUserId,
          xpiId: data.xpiId,
          id: data.id,
        };
      }
      this.indexValue = index;
      this.dialogVisible = true;
    },
    changeTab(e) {
      this.tabsValue = e;
      this.queryForm.appealStatus = e;
      this.queryForm.current = 20;
      this.queryForm.offset = 1;
      console.log("--切换--", this.queryForm.appealStatus);
      this.getList();
    },
    getPusher() {
      const url = `/government-platform-center/case/getCaseFlow`;
      this.$axios
        .post(
          url,
          { exceFlag: 0 },
          {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }
        )
        .then((res) => {
          console.log("获取申报事件--", res.data.data);
          this.pusherTimeData = res.data.data;
        });
    },
    formatTimeDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以要加1
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    onCancel() {
      this.dialogVisible = false;
      let parm = {
        appealBelong: "",
        appealStatus: "",
        appealType: "个人",
        contribute: "",
        getSocre: null,
        getType: null,
        // pusherTime: '',
      };
    },
    // ---------------弹窗
    rowSelectedChange2(_, row) {
      this.selectedInputItemValue2 = row[0];
    },
    changePage2(e) {
      this.queryForm2.offset = e;
      this.selectEvent();
    },
    selectEvent() {
      this.eventVisible = true;
      this.loading2 = true;
      const url = `/government-platform-center/case/getCaseFlow`;
      this.$axios
        .post(
          url,
          { exceFlag: 0 },
          {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData2 = res.data.data;
            this.total2 = res.data.total;
          }
        })
        .finally(() => {
          this.loading2 = false;
        });
    },
    //实践操作
    putEvent() {
      (this.dataDialogFrom.xpiId = this.selectedInputItemValue2.eventId),
        console.log(this.selectedInputItemValue2);
      this.eventVisible = false;
    },
    // 申诉审核
    clickCont(index, text) {
      const that = this;
      Modal.confirm({
        title: "温馨提示",
        content: index == 1 ? "确定审核通过吗" : "确定审核不通过吗",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          const url = `/government-platform-center/socreAppeal/edit`;
          that.$axios
            .post(
              url,
              { id: text.id, appealStatus: index },
              {
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              }
            )
            .then((res) => {
              if (res.data.code == 0) {
                that.$message.success("操作成功");
                that.reset();
              }
            });
        },
        onCancel() {
          // 在此处理取消逻辑
          // console.log('删除已取消')
        },
      });
    },
    // 驳回
    clickCont2(text) {
      this.dataDialogFrom = text;
      this.dialogVisible = true;
    },
    handleSubmit() {
      let text = this.dataDialogFrom;
      if (!text.checkDesc) {
        message.error("请输入驳回原因");
      }
      const url = `/government-platform-center/socreAppeal/edit`;
      this.$axios
        .post(
          url,
          { id: text.id, checkDesc: text.checkDesc, appealStatus: 2 },
          {
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
          }
        )
        .then((res) => {
          if (res.data.code == 0) {
            this.dialogVisible = false;
            this.$message.success("操作成功");
            this.reset();
          }else{
            this.$message.success("操作失败，请稍后重试！");

          }
        });
    },
  },
};
</script>
<style scoped>
.ant-row {
  border-radius: 5px;
  margin-bottom: 15px;
  background: #fff;
  padding: 20px;
  color: #000;
}

.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/deep/ .ant-table-thead > tr > th {
  color: #000;
  font-weight: bold;
}

/deep/ .ant-table-tbody > tr > td {
  color: #000;
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}
.table {
  width: 100%;
  overflow-x: auto !important;
}

/* 添加表格原生滚动条样式 */
::v-deep .ant-table-body {
  overflow-x: auto !important;
  /* overflow-y: auto !important; */
  /* max-height: 500px; 设置最大高度，超出时显示垂直滚动条 */
}

/* 确保使用原生滚动条样式 */
::v-deep .ant-table-body::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::v-deep .ant-table-body::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;
  border-radius: 4px;
}

::v-deep .ant-table-body::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}

/* 修复固定列的问题 */
::v-deep .ant-table-fixed-right {
  right: 0px; /* 为滚动条留出空间 */
}
</style>
